<template>
  <Form
    class="xtx-form"
    :validation-schema="mySchema"
    autocomplete="off"
    v-slot="{ errors }"
    ref="formCom"
  >
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{ nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          :class="{ err: errors.mobile }"
          v-model="form.mobile"
          name="mobile"
          class="input"
          type="text"
          placeholder="绑定的手机号"
        />
      </div>
      <div v-if="errors.mobile" class="error">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          :class="{ err: errors.code }"
          v-model="form.code"
          name="code"
          class="input"
          type="text"
          placeholder="短信验证码"
        />
        <span class="code" @click="send">{{
          time === 0 ? "发送验证码" : `${time}秒后重发`
        }}</span>
      </div>
      <div v-if="errors.code" class="error">{{ errors.code }}</div>
      <!-- <div class="error"></div> -->
    </div>
    <a @click="submit" href="javascript:;" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import QC from 'qc'
import { reactive, ref, onUnmounted } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/core'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'CallbackBind',
  components: { Form, Field },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 1.准备一些信息 openId(unionId) qq头像 昵称
    // 2.完成表单校验
    // 3.发送验证码 先校验 再做api 调用 倒计时
    // 4.进行绑定 绑定成功就是登录成功
    const nickname = ref('null')
    const avatar = ref('null')
    if (QC.Login.check()) {
      QC.api('get_user_info').success(res => {
        avatar.value = res.data.figureurl_1
        nickname.value = res.data.nickname
      })
    }
    // 表单数据对象
    const form = reactive({
      mobile: null,
      code: null
    })
    // 校验规则对象
    const mySchema = {
      mobile: schema.mobile,
      code: schema.code
    }
    // 发送短信验证码
    // start 开启 stop 停止
    // 回调函数 执行间隔 是否立即开启
    // 1.发送验证码
    // 1.1绑定发送验证码点击事件
    // 1.2校验手机号 成功发送短信(定义api) 请求成功开启60秒倒计时 不能再次点击 结束 恢复原样
    // 1.3 校验失败 校验样式显示出来
    const time = ref(0)
    const formCom = ref(null)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, false)

    onUnmounted(() => {
      pause()
    })
    // 发送短信
    const send = async () => {
      const valid = schema.mobile(form.mobile)
      if (valid === true) {
        // 通过
        if (time.value === 0) {
          // 没有倒计时 才可以发送请求
          await userQQBindCode(form.mobile)
          Message({ type: 'success', text: '发送成功' })
          time.value = 60
          resume()
        }
      } else {
        // 未通过 触发vee的错误函数 显示错误信息
        // setFieldError(字段,错误信息)
        formCom.value.setFieldError('mobile', valid)
      }
    }
    // -------------------------------------
    // 立即绑定
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      const valid = await formCom.value.validate()
      // console.log(valid)
      if (valid) {
        // console.log(1)
        // 校验成功 发送请求
        userQQBindLogin({ unionId: props.unionId, ...form }).then(data => {
          // 实现和之前登录一样的逻辑
          // 存储用户信息
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })

          store.dispatch('cart/mergeLocalCart').then(() => {
            // 跳转 来源也或首页
            router.push(store.state.user.redirectUrl || '/')
            // 消息提示
            Message({ type: 'success', text: 'QQ绑定成功' })
          })
        }).catch(e => {
          Message({ type: 'error', text: '绑定失败' })
        })
      }
    }
    return { nickname, avatar, form, mySchema, send, time, formCom, submit }
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
